#!/usr/bin/python3
from openpyxl import load_workbook
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Sort(Base_Plugin):
    def __init__(self, context) -> None:
        super().__init__()
        self.context = context
        self.inside_sheets = self.context["inside_sheets"]

    def run(self, workspace, source):
        ignores = self.inside_sheets
        based_on = list()
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]
        for row in _directory.rows:
            table_name = row[2].value
            if table_name != "描述" and table_name is not None:
                based_on.append(table_name.strip())

        based_on.insert(0, ignores[0])
        for idx in range(1, len(ignores)):
            based_on.append(ignores[idx])

        if "".join(based_on) != "".join(workbook.sheetnames):
            self.processed += 1
            for idx, sheet_name in enumerate(based_on, 0):
                offset = idx - workbook.sheetnames.index(sheet_name)
                workbook.move_sheet(sheet_name, offset)

        return_val = None
        if self.processed > 0:
            saved_name = r"Sorted.xlsx"
            new_path = os.path.join(workspace, saved_name)
            if os.path.exists(new_path):
                os.remove(new_path)
            workbook.save(new_path)
            return_val = saved_name
        else:
            return_val = source
        del workbook
        gc.collect()
        return return_val
